//
//  ZYCategorySecondPageController.m
//  Adorable_Things
//
//  Created by huzhiyan on 16/1/11.
//  Copyright © 2016年 Banana Inc. All rights reserved.
//

#import "ZYCategorySecondPageController.h"
#import "ZYCategorySecondPageModel.h"
#import "ATLoginViewController.h"
#import "ZYCategorySecondCollectionViewCell.h"
#import "ZYCategoryMainCollectionViewCell.h"
#import "ZYCategorySecondCollectionReusableView.h"
#import "ATMainDetailViewController.h"
#import "ZYCategoryHeaderView.h"


@interface ZYCategorySecondPageController () <UICollectionViewDataSource,UICollectionViewDelegate,UIGestureRecognizerDelegate,UICollectionViewDelegateFlowLayout,ZYCategoryCollectionReusableViewDelgate,ATMainDetailViewControllerDelegate>

@property (nonatomic, strong) ZYCategoryHeaderView *headerView;
@property (nonatomic, strong) NSMutableArray *dataModelArray;
@property (nonatomic, strong) NSMutableArray *headerModelArray;
@property (nonatomic, assign) NSInteger page;
// 判断是否只刷新下面
@property (nonatomic, assign) BOOL isRefreshView;

@property (nonatomic, strong) NSString *item_id;

@end

@implementation ZYCategorySecondPageController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _page = 0;
    _dataModelArray = [NSMutableArray array];
    [self addSubCollectionViewItemSize];
    [self addSubHeaderView];
    [self setUpData];
    
    // 下拉刷新
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _page = 0;
        [self setUpData];
    }];
    // 上拉加载
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page += 1;
        [self setUpData];
    }];
}

#pragma mark ---  添加导航自定义视图
// 添加导航自定义视图
- (void)addSubHeaderView
{
    _headerView = [[ZYCategoryHeaderView alloc] initWithFrame:CGRectMake(0, 20, kWidth, 45)];
    [self.view addSubview:_headerView];
    [_headerView.backItemButton addTarget:self action:@selector(backItemButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];

}


- (void)backItemButtonClick:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark ---  请求数据
- (void)setUpData
{
    NSMutableDictionary *parentDic = [NSMutableDictionary dictionary];
    parentDic[@"category_id"] = _category_id;
    parentDic[@"order_by=1"] = @"1";
    parentDic[@"order_desc"] = @"1";
    parentDic[@"page"] = [NSString stringWithFormat:@"%ld",_page];
    parentDic[@"page_size"] = @"20";
    parentDic[@"q"] = @"";
    if ([ATUserManager shareManager].isLogin) {
        parentDic[@"auth_token"] = [ATUserManager shareManager].auth_token;
    }

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:@"http://api.menghuoapp.com/v1/item/search" parameters:parentDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic  = (NSDictionary *)responseObject;
        NSArray *dataArr = dic[@"data"];
        if (_page == 0) {
            [_dataModelArray removeAllObjects];
            _page = 0;
        }
        for (NSDictionary *dataDic in dataArr) {
            ZYCategorySecondPageModel *model = [[ZYCategorySecondPageModel alloc] init];
            [model setValuesForKeysWithDictionary:dataDic];
            [_dataModelArray addObject:model];
        }
        [_collectionView.mj_footer endRefreshing];
        [_collectionView.mj_header endRefreshing];
        [_collectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark ---  取消添加收藏
- (void)cancelAndLikeButton:(ZYCategorySecondPageModel *)model
{
    if ([ATUserManager shareManager].isLogin) {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"auth_token"] = [ATUserManager shareManager].auth_token;
    dic[@"item_id"] = _item_id;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        if ([model.favorite integerValue] == 0) {
            [manager POST:@"http://api.menghuoapp.com/v1/item/mark" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self setUpData];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            }];
        } else {
            [manager POST:@"http://api.menghuoapp.com/v1/item/unmark" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                [self setUpData];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            }];
        }
    } else {
        ATLoginViewController *loginVC = [[ATLoginViewController alloc] init];
        UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        loginVC.navigationController.navigationBar.hidden = YES;
        [self presentViewController:naVC animated:YES completion:nil];
        
    }


}

#pragma mark ---  添加collectionView视图
- (void)addSubCollectionViewItemSize
{
    self.collectionView.backgroundColor = [UIColor clearColor];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.collectionView.collectionViewLayout = flowLayout;
    flowLayout.itemSize = CGSizeMake((kWidth - 50) / 2, (kWidth - 50) / 2 + 85);
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 20, 20, 20);
    flowLayout.headerReferenceSize = CGSizeMake(kWidth, kWidth / 3.75);
    [self.collectionView registerNib:[UINib nibWithNibName:@"ZYCategorySecondCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"ZYCategorySecondCollectionViewCell"];
    [self.collectionView registerClass:[ZYCategorySecondCollectionReusableView class]forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ZYCategorySecondCollectionReusableView"];
}

#pragma mark ---  UICollectionViewDataSource,UICollectionViewDelegate代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataModelArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZYCategorySecondCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZYCategorySecondCollectionViewCell" forIndexPath:indexPath];
    ZYCategorySecondPageModel *model = _dataModelArray[indexPath.row];
    cell.model = model;
    cell.block = ^ void (NSString *itemID) {
        self.item_id = itemID;
        [self cancelAndLikeButton:model];
    };
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        ZYCategorySecondCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ZYCategorySecondCollectionReusableView" forIndexPath:indexPath];
        // 当点击下面时不刷新表头
        if (!_isRefreshView) {
            header.parent_id = _category_id;
        }
        header.delegate = self;
        return header;
    }
    
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(kWidth, kWidth / 3.75);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZYCategorySecondPageModel *model = _dataModelArray[indexPath.row];
    ATMainDetailViewController *mainDetailVC = [[ATMainDetailViewController alloc] init];
    mainDetailVC.secondModel = model;
    mainDetailVC.item_id = model.item_id;
    mainDetailVC.delegte = self;
    [self.navigationController pushViewController:mainDetailVC animated:YES];
}

#pragma mark ---  UIGestureRecognizerDelegate代理方法
- (void)ZYCategoryCollectionReusableView:(ZYCategorySecondCollectionReusableView *)reusableView parentID:(NSString *)parentID
{
    _isRefreshView = YES;
    self.category_id = parentID;
    [self setUpData];

}

#pragma mark ---  ATMainDetailViewControllerDelegate代理方法
- (void)refreshViewController
{
    [self setUpData];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
